#include <iostream>
#include <WinSock2.h>
#include <WS2tcpip.h>
#pragma comment(lib,"Ws2_32.lib")

int main()
{
    // 加载套接字库
    WORD wVersionRequested = MAKEWORD(1, 1);
    WSADATA wsaData;
    int err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0)
    {
        return -1;
    }
    if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
    {
        WSACleanup();
        return -1;
    }
    // 创建套接字
    SOCKET sockSrv = socket(AF_INET,SOCK_DGRAM, IPPROTO_UDP);
    SOCKADDR_IN addrSrv;
    addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    addrSrv.sin_family = AF_INET;
    addrSrv.sin_port = htons(6000);
    // 绑定套接字
    bind(sockSrv, reinterpret_cast<SOCKADDR*>(&addrSrv), sizeof(SOCKADDR));

    char recvBuf[100];
    SOCKADDR_IN addrClient;
    int len = sizeof(SOCKADDR);
    while (true)
    {
        // 等待并接收数据
        recvfrom(sockSrv, recvBuf, 100, 0, reinterpret_cast<SOCKADDR*>(&addrClient), &len);
        printf("recvfrom: %s\n", recvBuf);
    }
    closesocket(sockSrv);
    WSACleanup();
    return 0;
}
